<template>
	<view class="content">
		<view class="uploaddiv" @click="openupload()"  v-if="showadd()">
			<view style="display: flex; justify-content: center; padding: 8rpx;">
				<uni-icons type="camera-filled" size="38" color="white"></uni-icons>
			</view>
		</view>

		<u-skeleton rows="15" title :loading=loading v-if="loading"></u-skeleton>

		<view class="head" v-if="!loading">
			<view class="haohaocontent">
				<view class="circle">

				</view>
				<view class="circle2">
					<text style="font-weight:bold; color:white">李泽昊</text>
				</view>
			</view>

		</view>

		<view class="item" v-if="!loading">
			<view class="main" v-for="(item,index) in aritlelist" :key="item.id">
				<view class="round-dot"></view>
				<view class="realcontent">
					<text style="font-weight: bold;">{{formatDateMethod(item.recordtime) }}</text>
					<text
						style="font-size :0.8em; color: #8f8f94; margin-left: 15rpx;">{{calculateDateDis(item.recordtime)}}</text>
				</view>
				<!--图片1张-->
				<view class="iamgearea" v-if="item.url.length==1 && item.type=='img'" @click="preview(item.url)">
					<image class="imgshow" :src="item.url[0]" mode="widthFix"></image>
				</view>
				<!--图片2张-->
				<view class="iamgearea2" v-if="item.url.length==2 && item.type=='img'">
					<view class="imgshow2">
						<image  @click="preview(item.url,0)" class="imgshow2pic" :src="item.url[0]" mode="scaleToFill"
							style="border-top-left-radius: 20rpx; height: 375rpx;"></image>
					</view>
					<view class="imgshow2">
						<image  @click="preview(item.url,1)" class="imgshow2pic" :src="item.url[1]" mode="scaleToFill"
							style="border-top-right-radius: 20rpx; height: 375rpx;"></image>
					</view>
				</view>

				<!--图片>=3张-->
				<view class="iamgearea2" v-if="item.url.length>=3 && item.type=='img'" >
					<view class="imgshow3" v-for="(picurl,index) in item.url ">
						<image @click="preview(item.url,index)" class="imgshow2pic" :src="picurl" mode="aspectFill" :class="[albumClass(index)]"
							style="height: 240rpx;"></image>
					</view>
				</view>

				<view class="iamgearea" v-if="item.type=='video'">
					<view style="width: 100%;">
						<video :title=item.content :show-fullscreen-btn="false"  :id=item.id style="width:100%;height:450rpx;" @ended="end(item.id)" @play="playFullscreen(item.id)" @fullscreenchange="fullchange"
							object-fit=cover :src="item.url[0]"></video>
						
					</view>

				</view>

				<view class="imagetitle">
					<view style="padding: 20rpx;"><text style="font-size:0.9em;">{{item.content}}</text></view>
					<view class="zancontainer">
						<view class="zan"  @click="editartile(item.id,item.type,item.userid)">
							<uni-icons type="auth" color=""  size="16" style=" vertical-align: middle;" v-if="isuser(item.userid)"></uni-icons>
							<uni-icons type="locked" color=""  size="16" style=" vertical-align: middle;" v-else></uni-icons>
							
							<text style="font-size:0.8em; color: #8f8f94; line-height: 46rpx; ">
								{{item.username}}</text>
						</view>
						<view class="zan" style="margin-left: -50rpx;" v-if="showadd()">
							<view class="zanchild" @click="likes(item)">
								<uni-icons type="heart-filled" size="16" style=" vertical-align: middle;"
									color="#FF85BD" v-if="showlike(item.like)"></uni-icons> 
								<uni-icons type="heart" size="16" style=" vertical-align: middle;" v-if="!showlike(item.like)"></uni-icons>
								<text style="font-size:0.8em; color: #8f8f94;">赞</text>
							</view>
							<view class="zanchild" @click="addcomment(item.id)">
								<uni-icons type="chat" size="16" style=" vertical-align: middle;">
								</uni-icons>
								<text style="font-size:0.8em; color: #8f8f94;text-align: center;">评论</text>

							</view>
							<view class="zanchild" style="margin-left: 15rpx;">
								<!-- <uni-icons type="chat" size="16" style=" vertical-align: middle;">
								</uni-icons> -->
								<view style="display: flex;">
									<view style="margin-top:-5rpx;">
										<uni-icons type="compose"   size="16" style=" vertical-align: middle;">
										</uni-icons>
									</view>
									<view>
										<button open-type="share" style="color: #8f8f94;border: none; padding: 0rpx;margin-top: -7rpx; font-size: 0.8rem;" :plain="true" size="mini">分享</button>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="commentcontanier" v-if="commentmap[item.id]&&commentmap[item.id].length>0">
						<view class="comment" v-for="item1 in commentmap[item.id]" :key="item1.id">
							<text @click="editcomment(item.id,item1.id,item1.publishuserid)"
								style="font-size:1em; color: #4F7CB0; text-align: center;">{{ item1.publishuser}}:</text>
							<text style="font-size:1em; color: #8f8f94; text-align: center;">{{item1.content}}</text>
						</view>
					</view>

					<view style="height:20rpx;">
					</view>



				</view>

			</view>
		</view>


		<!--pinglu-->
		<u-popup overlayOpacity=0 :show="commnetpopstatus" @close="close" @open="open" style="width: 700rpx;">
			<view
				style="height:90rpx;display: flex;align-items: center; justify-content: center;width: 700rpx; padding: 20rpx;">
				<view style="flex:0 0 70%;height: 100%;display: flex;align-items:center">
					<input :adjust-position="false" cursor-spacing="20" v-model="commentcontent" class="uni-input"
						:focus="focus"  id="inputclass" @blur="handleBlur" placeholder="说点什么" />
				</view>
				<view style="flex:0 0 30%;height: 100%;display: flex;align-items: center;">
					<button @click="pub" class="mini-btn" size="mini" type="warn"
						style="display:block;margin:0 auto">发布</button>
				</view>
			</view>

			<view class="keyboard" :style="{height: keyboardHeight + 'px' }">
			</view>

		</u-popup>

		<!--上穿-->
		<u-popup :show="uploadpopupstatus" @close="closeupload" @open="openupload" round=10 bgColor="#ffffff">
			<view style="display: flex; padding: 38rpx;">
				<view class="uploadchild"> </view>
				<view class="uploadchild" style="flex-direction: column;" @click="choiceImg">
					<view style="background:#FF5A91;border-radius: 50%;padding: 20rpx;">
						<uni-icons type="image" size="52" color="white"></uni-icons>
					</view>
					<view>
						<text>发照片</text>
					</view>
				</view>
				<view class="uploadchild">

				</view>
				<view class="uploadchild" style="flex-direction: column;" @click="choiceVideo">
					<view style="background:#C97FFF;border-radius: 50%; padding: 20rpx;">
						<uni-icons type="videocam" size="52" color="white"></uni-icons>
					</view>
					<view>
						<text>发视频</text>
					</view>
				</view>
				<view class="uploadchild"> </view>
			</view>
		</u-popup>



	</view>
</template>

<script>
	import * as utils from '../../util/util.js';

	export default {
		data() {
			return {
				loading: true,
				commentcontent: '',
				focus: false,
				commnetpopstatus: false,
				uploadpopupstatus: false,
				commentArticleId: -1,
				aritlelist: [],
				commentList: [],
				commentmap: {},
				pageIndex: 1,
				total:1,
				keyboardHeight: 300,
				loadingnextpage:false
			}
		},
		onLoad() {
			uni.onKeyboardHeightChange(res => {
				console.log(res.height);
				//if (res.height > 0) {
					this.keyboardHeight = res.height;
				//}
			})
			//uni.hideTabBar();
			this.init();
		},
		
		onPullDownRefresh(){
			this.loadingnextpage = false;
			this.pageIndex =1;
			this.aritlelist = [];
			this.commentmap = {};
			this.init();
			uni.stopPullDownRefresh();
		},
		onReachBottom(){
			console.log(this.pageIndex);
			console.log(this.total);
			if(this.loadingnextpage){
				return;
			}
			
			this.loadingnextpage = true;
			this.pageIndex++;
			
			if(this.pageIndex >= this.total+1){
				this.loadingnextpage = false;
				return;
			}
			
			uni.showLoading({
				title: '加载中'
			});
			console.log("到底了");
			
			
			
			this.init();
			
		},
		methods: {
			showadd(){
				return utils.show();
			},
			isuser(userid){
				return userid==uni.getStorageSync('token')
			},
			likes(para){
				if(!utils.islogin()){
					uni.navigateTo({
						url:'/pages/index/login/login'
					})
					return;
				}
				if(para.like.includes(utils.getLoginInfo().id)){
					console.log("remove");
					para.like = para.like.filter(item=>item!=utils.getLoginInfo().id)
				}else{
					console.log("add");
					para.like.push(utils.getLoginInfo().id)
				}
				
			},
			showlike(para){
				if(!utils.islogin()){
					return false;
				}
				return para.includes(utils.getLoginInfo().id)
			},
			share(conent){
				console.log("11");
				uni.showShareMenu({
					withShareTicket:true,
					title:conent,
					success() {
						console.log("success")
					},fail(err) {
						console.log("err")
					}
				})
			},
			playFullscreen(id) {
				console.log("id");
				const v = uni.createVideoContext(id, this);
				
				v.requestFullScreen();

			},
			
			fullchange(e) {
				console.log(e.currentTarget.id);
				if (!e.detail.fullScreen) {
						const v = uni.createVideoContext(e.currentTarget.id, this);
						v.pause();
						v.exitFullScreen();
				}
			
			},
			end(id){
				const v = uni.createVideoContext(id, this);
				v.pause();
				v.exitFullScreen();
			},
			init() {
				var _this = this;
				utils.getList({
					"pageIndex": this.pageIndex
				}).then(
					function(res) {
						const total = res.result.total.total;
						const totalpage =total%5==0?total/5:parseInt(total/5)+1;
						_this.total = totalpage;
						
						const list = res.result.data;
						_this.aritlelist.push(...list);
						console.log(_this.aritlelist.length);
						const listid = list.map(item => {
							return item.id
						});
						//评论显示
						utils.getComment(listid).then(res => {
							const commentresult = res.result.data;
							_this.loading = false;
							
							if (commentresult.length > 0) {
								console.log(commentresult);
								_this.commentList.push(...commentresult);
								console.log(_this.commentList);

								//聚合评论id在文章中展示
								const aggregated = commentresult.reduce((acc, item) => {
									acc[item.artileid] = acc[item.artileid] || [];
									acc[item.artileid].push(item);
									return acc;
								}, {});

								//没有评论的文章 添加[],否则无法更新视图
								list.forEach((item) => {
									if (!aggregated[item.id]) {
										aggregated[item.id] = [];
									}
								});
								//_this.commentmap = aggregated;
								_this.commentmap = Object.assign({}, _this.commentmap, aggregated);
								console.log(_this.commentmap);
							}else{
								const map = {};
								list.forEach((item) => {
								     map[item.id] = [];
								});
								_this.commentmap = Object.assign({}, _this.commentmap, map);
							}
							
							setTimeout(function () {
								uni.hideLoading();
							}, 500);
							_this.loadingnextpage = false;

						})
					});
			},
			
			
			editartile(id,type,userid){
				if(!utils.islogin()){
				    uni.navigateTo({
				    	url:'/pages/index/login/login'
				    })				
					return;
				}
				console.log(userid);
				console.log(uni.getStorageSync('token'));
				if(userid!=uni.getStorageSync('token')){
					utils.toastwarn("您非作者");
					return;
				}
				
				if(type=='img'){
					uni.navigateTo({
						url:'/pages/index/editimg?type=edit&id='+id
					})
				}else{
					uni.navigateTo({
						url:'/pages/index/video?type=edit&id='+id
					})
				}
			},
			preview(pic,index) {
				console.log(pic+"ss"+index);
				utils.previewImage(pic,index);
			},
			albumClass(index) {
				return utils.albumClass(index);
			},
			handleBlur() {
				this.close();
			},
			choiceVideo() {
				//https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage
				//信小程序从基础库 2.21.0 开始， wx.chooseImage 停止维护，请使用 uni.chooseMedia 代替。
				console.log("video");
				//uin.chooseMedia
				uni.chooseVideo({
					count: 1, // 默认为9，设置图片的数量
					mediaType: ['video'], // 指定媒体类型为视频
					sourceType: ['album', 'camera'], // 指定视频来源为相册或相机
					success: (res) => {
						// 返回选定视频的临时文件路径,微信和h5不一样
						console.log(res);
						let videourl = res.tempFilePath;
						uniCloud.uploadFile({
							filePath: videourl,
							cloudPath: 're.mp4',
							success(res) {
								const queryString = encodeURIComponent(JSON.stringify(res));//model1代表对象
								uni.navigateTo({
									url: `/pages/index/video?path=${queryString}`
								});
							},
							fail(e) {
								console.log(e);
							}
						})
						//在起始页面跳转到test.vue页面并传递参数
						//url: '/pages/index/screen?id=' + para
						

					},
					fail: (err) => {
						console.error('选择视频失败：', err);
					}
				});
			},
			choiceImg() {
				let _that = this;
				_that.closeupload();
				uni.navigateTo({
					url: '/pages/index/editimg?type=add'
				});
			},



			formatDateMethod(params1) {
				var arr = params1.split("-");
				var str = arr[0] + "年" + arr[1].replace(/^0+/, '') + "月" + arr[2].replace(/^0+/, '') + "日";
				return str;
			},

			calculateDateDis(params1) {
				const startDate = new Date('2022-10-08');
				const endDate = new Date(params1);
				let diff = endDate - startDate;
				// 转换毫秒为年、月、日
				const years = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25)); // 考虑到闰年
				diff -= years * (1000 * 60 * 60 * 24 * 365.25);
				const months = Math.floor(diff / (1000 * 60 * 60 * 24 * 30.436875)); // 平均每月天数
				diff -= months * (1000 * 60 * 60 * 24 * 30.436875);
				const days = Math.floor(diff / (1000 * 60 * 60 * 24));

				return `${years}岁${months}个月${days}天`;
			},

			editcomment(artid,commentid,userid) {
				console.log(userid);
				 if(uni.getStorageSync('token')!=userid){
					 utils.toastwarn("您非作者");
					return;
				}
				var _this = this;
				uni.showActionSheet({
					title:"是否删除这条评论",
					itemList: ['删除'],
					success: function (res) {
						 uniCloud.callFunction({
								name:"delcomment",
								data: {
									"id":commentid,
								}
							}).then(r=>{
								utils.toast("删除成功");
								_this.commentmap[artid] = _this.commentmap[artid].filter(item=>item.id!=commentid);
							}).catch(er=>{
								utils.toastwarn("删除失败"+er);
							})
						
					},
					fail: function (res) {
						console.log(res.errMsg);
					}
				});
				
			},

			//评论弹窗
			addcomment(id) {
				if(!utils.islogin()){
	                uni.navigateTo({
	                	url:'/pages/index/login/login'
	                })				
					return;
				}
				console.log(utils.getLoginInfo())
				this.commnetpopstatus = true;
				this.commentArticleId = id;
				this.focus = false;
				 setTimeout(() => {
					this.focus = true; // this.secondFocus 是第二个文本框的 focus 属性。
				}, 0)
			},

			//发布
			pub() {
				console.log("发表评论" + this.commentArticleId);
				let arr = this.commentmap[this.commentArticleId];
				utils.addcomment({
					"artileid": this.commentArticleId,
					"content": this.commentcontent,
					"publishuser": utils.getLoginInfo().username,
					"publishuserid": utils.getLoginInfo().id
				}).then(res => {
					console.log(res);
					arr.unshift({
						artileid: this.commentArticleId,
						content: this.commentcontent,
						publishuser: utils.getLoginInfo().username,
						publishuserid:utils.getLoginInfo().id,
						id:res.result.id
					})
				}).catch(er => {
					utils.toastwarn("评论失败" + er);
				})


				this.commnetpopstatus = false;
			},
			//评论弹层
			close() {
				console.log("关闭");
				this.commnetpopstatus = false

				// console.log('close');
			},

			open() {

			},
			//上传弹层	
			openupload() {
				if(!utils.islogin()){
				    uni.navigateTo({
				    	url:'/pages/index/login/login'
				    })				
					return;
				}
				this.uploadpopupstatus = true;
			},

			closeupload() {
				this.uploadpopupstatus = false;

			}

		}
	}
</script>

<style lang="scss" scoped>
	.keyboard {
		width: 100%;
	}

	.pic1thborder {
		border-top-left-radius: 20rpx;
		height: 240rpx;
	}

	.popupShow {
		overflow: hidden;
		position: fixed;
	}

	.pic3thborder {
		border-top-right-radius: 20rpx;
		height: 240rpx;
	}



	.imgshow2 {
		width: 49.8%;
	}

	.imgshow3 {
		width: 32.9%;
	}

	.imgshow2pic {
		width: 100%;
	}

	.iamgearea2 {
		margin-top: 10rpx;
		width: 700rpx;
		display: flex;
		gap: 1rpx;
		font-size: 0;
		flex-wrap: wrap;
		justify-content: flex-start;
		background-color: white;
		border-top-left-radius: 28rpx;
		border-top-right-radius: 28rpx;
		box-sizing: border-box;
	}

	#inputclass {
		width: 90%;
		height: 60rpx;
		background-color: #F2F2F5;
		border-top-left-radius: 28rpx;
		border-top-right-radius: 28rpx;
		border-bottom-left-radius: 28rpx;
		border-bottom-right-radius: 28rpx;
	}

	.uploadchild {
		display: flex;

		justify-content: center;
		align-items: center;
		flex-grow: 1;
		height: 250rpx;
	}

	.uploaddiv {
		width: 90rpx;
		height: 90rpx;
		background: #FF5A91;
		position: fixed;
		right: 25rpx;
		bottom: calc(var(--window-bottom) + 50rpx);
		z-index: 10;
		border-radius: 50%;
	}

	.commentcontanier {
		width: 93%;
		background-color: #F2F2F5;
		//margin-top: 15rpx;
		margin-left: 15rpx;
		border-top-left-radius: 18rpx;
		border-bottom-left-radius: 18rpx;
		padding: 10rpx;
	}

	.comment {
		width: 70%;
		padding: 10rpx;
	}

	.imagetitle {
		display: flex;
		flex-direction: column;
		border-bottom-left-radius: 20rpx;
		border-bottom-right-radius: 20rpx;
	}

	.zancontainer {
		display: flex;
		flex-direction: row;
		padding: 10rpx;
		flex: 1;
		width: 100%;
	}


	.zan {
		display: flex;
		flex-direction: row;
		white-space: nowrap;
		margin-left: 15rpx;
		width: 50%;

		// padding: 10rpx;
		.zanchild {
			flex: 1;
			/* 所有子元素将等分父容器的空间 */
			//border: 1rpx solid red; /* 为了清晰地显示每个子元素 */
			//padding: 15rpx; /* 内边距 */
			//margin-left: 75rpx; /* 外边距 */
		}
	}

	.imagetitle {
		background-color: white;
		width: 700rpx;
		//border: 1rpx solid red;
	}

	.imgshow {
		width: 100%;
		height: auto;
		background-color: white;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
	}

	.round-dot {
		position: absolute;
		top: -1rpx;
		left: -10rpx;
		width: 10px;
		height: 10px;
		background-color: #FF7CB3;
		border-radius: 50%;
		z-index: 1;
	}

	.content {
		background-color: #F2F2F5;

		.head {
			background-color: #8f8f94;
			height: 550rpx;
			background-image: url('');
			background-size: cover;
			background-position: center;
			display: flex;
			flex-direction: column;
			align-items: left;
			justify-content: center;

			.haohaocontent {
				padding: 15rpx;
				display: flex;

				.circle {
					width: 50px;
					/* 设置宽度 */
					height: 50px;
					/* 设置高度与宽度相同以形成完美的圆 */
					//background-color: #3498db; /* 设置背景颜色 */
					border-radius: 50%;
					/* 设置边框半径为50%，形成圆形 */
					background-image: url('');
					background-size: cover;
					background-position: center;
					margin-left: 45rpx
				}

				.circle2 {
					display: flex;
					align-items: center;
					margin-left: 25rpx;
				}

			}

		}

		.item {
			//background-color: #8f8f94;
			// border: 1px solid #8f8f94; /* 设置边框为1px实线，颜色为黑色 */
			padding: 10rpx;
			/* 内边距 */
			//margin: 10px; /* 外边距 */
			width: 740rpx;

			/* 宽度 */
			//height: 100px; /* 高度 */
			//box-sizing: border-box; /* 防止宽度和高度包含边框 */
			//border-left: 3rpx #8f8f94;
			.main {
				position: relative;
				border-left: 1px solid #8f8f94;
				/* 设置边框为1px实线，颜色为黑色 */
				padding: 15rpx;
				margin-left: 10rpx;
				/* 内边距 */
				//margin: 10px; /* 外边距 */
				width: 740rpx;

				/* 宽度 */
				//height: 100px; /* 高度 */
				//box-sizing: border-box; /* 防止宽度和高度包含边框 */
				.iamgearea {
					margin-top: 10rpx;
					width: 700rpx;
					font-size: 0;
					//padding: 10rpx;
					//border-radius: 100rpx; /* 设置弧度大小 */

				}
			}

		}
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		// margin-top: 200rpx;
		// margin-left: auto;
		// margin-right: auto;
		// margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.page-body {
		width: 350rpx;
	}
</style>